package orm

import (
	"app/daos"
	"app/utils"
	"fmt"
	"github.com/fwhezfwhez/errorx"
	"github.com/sirupsen/logrus"
	"os"
	"path/filepath"
	"reflect"
	"strings"
	"text/template"
	"time"
)

func ProcessTable(table daos.Orm, outDir string) {
	outDir = filepath.FromSlash(filepath.Clean(outDir))
	fileName := utils.FileNameFilter(table.TableName())
	filePath := fmt.Sprintf("%s/%s.go", outDir, fileName)
	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0644)
	if err != nil {
		logrus.Fatal(errorx.Wrap(err))
	}

	type Common struct {
		StructName string
		Time       string
	}

	structType := reflect.TypeOf(table)
	nameParts := strings.Split(structType.String(), ".")
	structName := nameParts[len(nameParts)-1]
	commonParams := Common{structName, time.Now().Format(time.DateTime)}
	tmpl, err := template.New("common").Parse(commonStr)
	if err != nil {
		logrus.Fatal(errorx.Wrap(err))
	}

	err = tmpl.Execute(file, commonParams)
	if err != nil {
		logrus.Fatal(errorx.Wrap(err))
	}
}
